package com.salt.modules.sys.web;

import com.salt.common.json.AjaxJson;
import com.salt.common.utils.StringUtils;
import com.salt.core.log.annotation.OperationRecord;
import com.salt.core.persistence.Page;
import com.salt.core.web.BaseController;
import com.salt.modules.sys.entity.MultiTenant;
import com.salt.modules.sys.entity.User;
import com.salt.modules.sys.service.MultiTenantService;
import com.salt.modules.sys.utils.UserUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 管理用户的租户权限（即查看多个公司的数据）Controller
 * @Author salt
 * @Date 2022/1/19
 * @Version 1.0.1
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sys/multi/tenant")
public class MultiTenantController extends BaseController {

    private final MultiTenantService multiTenantService;

    @GetMapping("page")
    public AjaxJson page(MultiTenant multiTenant, HttpServletRequest request, HttpServletResponse response) {
        Page<MultiTenant> page = multiTenantService.findPage(new Page<>(request, response), multiTenant);
        return AjaxJson.success().put("page", page);
    }

    @PostMapping("save")
    @OperationRecord(service = "系统服务", module = "租户管理", operation = "新增", description = "")
    public AjaxJson save(MultiTenant multiTenant) {
        if(StringUtils.isBlank(multiTenant.getId())) {
            MultiTenant tenant = multiTenantService.find(multiTenant);
            if (tenant != null)
                return AjaxJson.error("【" + multiTenant.getUser().getName() + "】已添加，不能重复添加!");
        }
        multiTenantService.save(multiTenant);
        return AjaxJson.success("【" + multiTenant.getUser().getName() + "】添加成功!");
    }

    @GetMapping("queryById")
    public AjaxJson queryById(MultiTenant multiTenant) {
        return AjaxJson.success().put("multiTenant", multiTenantService.get(multiTenant.getId()));
    }

    @DeleteMapping("delete")
    @OperationRecord(service = "系统服务", module = "租户管理", operation = "删除", description = "")
    public AjaxJson delete(MultiTenant multiTenant) {
        multiTenantService.delete(multiTenant);
        return AjaxJson.success("删除成功!");
    }

    @GetMapping("find")
    public AjaxJson find(MultiTenant multiTenant) {
        return AjaxJson.success().put("tenant", multiTenantService.find(multiTenant));
    }

    @GetMapping("isTenant")
    public AjaxJson isTenant() {
        User user = UserUtils.getUser();
        String isTenant = "0";
        if (user.isAdmin() || (multiTenantService.find(new MultiTenant(user)) != null))
            isTenant = "1";
        return AjaxJson.success().put("isTenant", isTenant);
    }

}
